#include <iostream>
#include <memory>
#include <string>

using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;
using std::string;

void test00()
{
    string msg = "hello,world\n";
    FILE *fp = fopen("wd.txt", "a+");
    fwrite(msg.c_str(), 1, msg.size(), fp);

    fclose(fp);
}

//删除器
struct FILECloser
{
    void operator()(FILE *fp)
    {
        if(fp)
        {
            fclose(fp);
            cout << "fclose(fp)" << endl;
        }
    }
};
void test()
{
    string msg = "hello,world\n";
    /* FILE *fp = fopen("wd.txt", "a+"); */
    unique_ptr<FILE, FILECloser> up(fopen("wd.txt", "a+"));
    //get函数可以从智能指针获取到裸指针
    fwrite(msg.c_str(), 1, msg.size(), up.get());
    /* fclose(up.get()); */
}

void test2()
{
    FILECloser fc;
    //要想从类型调用到对象，可以直接显示使用构造函数，比如：
    //使用无参构造函数
    string msg = "hello,world\n";
    /* shared_ptr<FILE> sp(fopen("wuhan.txt", "a+"), FILECloser()); */
    shared_ptr<FILE> sp(fopen("wuhan.txt", "a+"), fc);
    fwrite(msg.c_str(), 1, msg.size(), sp.get());
    /* fclose(sp.get()); */
}
int main(int argc, char **argv)
{
    test2();
    return 0;
}

